﻿import 'package:azring/core/controllers/ring_controller.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'edit_cards_state.dart';
import '../../../core/repository/default_api.dart';
import '../status_logic.dart';

/// 编辑卡片控制器
class EditCardsLogic extends GetxController {
  final EditCardsState state = EditCardsState();

  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  @override
  void onInit() {
    super.onInit();
    // 加载卡片配置
    _loadCardConfiguration();
  }

  /// 加载卡片配置
  Future<void> _loadCardConfiguration() async {
    try {
      state.isLoading.value = true;

      final response = await DefaultApi().queryLayoutListGet<dynamic>(
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null && data is List && data.isNotEmpty) {
          _parseCardConfiguration(data);
        } else {}
      }
    } catch (e) {
      print('❌ 加载卡片配置失败: $e');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 解析卡片配置（仅解析卡片数据模块中的小卡片）
  void _parseCardConfiguration(List<dynamic> data) {
    final displayedCards = <HealthCardItem>[];
    final hiddenCards = <HealthCardItem>[];

    // 定义卡片数据模块中的卡片名称
    final cardDataModules = ['心率', '心率变异性', '睡眠', '血氧饱和度', '活动', '锻炼记录', '生理周期'];

    // 按moduleSign排序
    data.sort((a, b) {
      final signA = int.tryParse(a['moduleSign']?.toString() ?? '999') ?? 999;
      final signB = int.tryParse(b['moduleSign']?.toString() ?? '999') ?? 999;
      return signA.compareTo(signB);
    });

    for (var item in data) {
      final moduleName = item['moduleName'] as String?;
      final moduleDisplay = item['moduleDisplay'] as String?;
      final isDisplayed = moduleDisplay == '0'; // 0表示显示，1表示不显示

      // 只处理卡片数据模块中的卡片
      if (moduleName != null && cardDataModules.contains(moduleName)) {
        final card = _createCardFromModuleName(moduleName, isDisplayed);
        if (card != null) {
          if (isDisplayed) {
            displayedCards.add(card);
          } else {
            hiddenCards.add(card);
          }
        }
      }
    }

    state.displayedCards.value = displayedCards;
    state.hiddenCards.value = hiddenCards;
  }

  /// 根据模块名称创建卡片（仅创建卡片数据模块中的卡片）
  HealthCardItem? _createCardFromModuleName(
      String moduleName, bool isDisplayed) {
    switch (moduleName) {
      case '心率':
        return HealthCardItem(
          id: 'heart_rate',
          title: '心率',
          icon: 'assets/status/hr.png',
          isDisplayed: isDisplayed,
        );
      case '心率变异性':
        return HealthCardItem(
          id: 'hrv',
          title: '心率变异性',
          icon: 'assets/status/hrv.png',
          isDisplayed: isDisplayed,
        );
      case '睡眠':
        return HealthCardItem(
          id: 'sleep',
          title: '睡眠',
          icon: 'assets/status/sleep.png',
          isDisplayed: isDisplayed,
        );
      case '血氧饱和度':
        return HealthCardItem(
          id: 'blood_oxygen',
          title: '血氧饱和度',
          icon: 'assets/status/bloodOxygen.png',
          isDisplayed: isDisplayed,
        );
      case '活动':
        return HealthCardItem(
          id: 'activity',
          title: '活动',
          icon: 'assets/status/activity.png',
          isDisplayed: isDisplayed,
        );
      case '锻炼记录':
        return HealthCardItem(
          id: 'workout_records',
          title: '锻炼记录',
          icon: 'assets/status/traing.png',
          isDisplayed: isDisplayed,
        );
      case '生理周期':
        return HealthCardItem(
          id: 'physiological_cycle',
          title: '生理周期',
          icon: 'assets/status/cycle.png',
          isDisplayed: isDisplayed,
        );
      default:
        return null;
    }
  }

  /// 保存卡片配置
  Future<void> saveCardConfiguration() async {
    try {
      state.isLoading.value = true;

      // 构建卡片配置数组
      final List<Map<String, dynamic>> layoutList = [];

      // 添加显示的卡片（按顺序）
      for (int i = 0; i < state.displayedCards.length; i++) {
        final card = state.displayedCards[i];
        layoutList.add({
          'moduleName': card.title,
          'moduleDisplay': '0', // 0表示显示
          'moduleSign': i.toString(), // 使用索引作为排序标识
          'sort': i + 1, // sort从1开始，对应位置
        });
        print('📝 添加显示卡片: ${card.title}, 顺序: $i, sort: ${i + 1}');
      }

      // 添加隐藏的卡片
      for (int i = 0; i < state.hiddenCards.length; i++) {
        final card = state.hiddenCards[i];
        layoutList.add({
          'moduleName': card.title,
          'moduleDisplay': '1', // 1表示不显示
          'moduleSign': (state.displayedCards.length + i).toString(),
          'sort': state.displayedCards.length + i + 1, // 继续递增sort值
        });
      }
      // 一次性发送所有卡片配置
      await DefaultApi().editLayoutPut<dynamic>(
        layoutList: layoutList,
        isShowLoading: true,
        isShowErrMsg: true,
      );

      // 刷新首页的布局配置
      if (Get.isRegistered<StatusLogic>()) {
        await Get.find<StatusLogic>().refreshModuleLayout();
      }

      Get.back(result: true);
    } catch (e) {
      Toast.show('保存失败，请重试');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 移动卡片到显示列表
  void moveCardToDisplayed(HealthCardItem card) {
    state.moveToDisplayed(card);
  }

  /// 移动卡片到隐藏列表
  void moveCardToHidden(HealthCardItem card) {
    state.moveToHidden(card);
  }

  /// 更新显示列表顺序
  void updateDisplayedOrder(List<HealthCardItem> newOrder) {
    state.updateDisplayedOrder(newOrder);
  }
}
